package com.android.xcalendar.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.android.xcalendar.R;
import com.android.xcalendar.util.XCalendarContentManager;

public class CalendarActivity extends Activity{
	Button bnLogin;
	EditText editUser, editPwd;
	String stringUser, stringPwd, url;
	XCalendarContentManager contentManager = XCalendarContentManager.getInstance();
	private ProgressDialog pDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		pDialog = new ProgressDialog(this);
		bnLogin = (Button) findViewById(R.id.button_login);
		editUser = (EditText) findViewById(R.id.edit_username);
		editPwd = (EditText) findViewById(R.id.edit_password);

		bnLogin.setOnClickListener(loginListener);
	}
	
	private OnClickListener loginListener = new OnClickListener()
	{
		@Override
		public void onClick(View v) {
			stringUser = editUser.getText().toString();
			stringPwd = editPwd.getText().toString();
			url = "http://xiaoyitest.appspot.com/resources/user/login/name="
				+ stringUser + "&password=" + stringPwd;
			new LoginAsyncTask().execute(url) ;
			
		}
	};
	
	private class LoginAsyncTask extends AsyncTask<String, String, String> {
		protected void onPreExecute() {
			if (pDialog != null) {
				pDialog = ProgressDialog.show(CalendarActivity.this, "", "Loading. Please wait...", true);
				pDialog.setCancelable(true);
				pDialog.setOnCancelListener(new OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {
						cancel(true);
						pDialog.dismiss();
					}
				});
			}
			
		}

		protected String doInBackground(String... urls) {
			contentManager.connect(urls[0]);
			return "";
		}

		protected void onPostExecute(String result) {
			pDialog.dismiss();
			if(contentManager.getJsonMessageFlag() == 1)
			{
				new AlertDialog.Builder(CalendarActivity.this)
				.setTitle("Login Error")
				.setMessage("username or password incorrect!")
				.setNeutralButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				}).show();
			
			}
			else{		
			Intent newIntent = new Intent(getApplicationContext(),MonthViewActivity.class);	
			startActivity(newIntent);
			finish();
			}
		}
	}
	

}